/**
 * create by young (young2f@outlook.com) on 2023/8/8
 */
'use strict';
const mqtt = require('./mqttClient');
const _ = require('lodash');

const tenantCode = 'TEN230722214916D471';
const host = 'http://treec.cn:18008';
const spaceTime = 1000 * 33*4;
setInterval(() => {
    main();
}, spaceTime);
main();

function main() {
    var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
    var req = new XMLHttpRequest();
    req.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            // console.log(req.responseText);
            const res = JSON.parse(req.responseText);
            const {result = {}} = res;

            const {devices = []} = result;
            _.map(devices, item => {
                const temp = getData(item);

                console.log(temp);
                const {data, topic} = temp;
                mqtt.sendData(topic, data);
            });

        }
    };
    req.open('POST', host + '/api/device/find/page', true);
    req.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
    req.send(JSON.stringify({tenantCode, skip: 0, limit: 200}));
}

function getData(device) {
    /**
     *   {
    accessMode: 'r',
    createDate: 1681442468202,
    dataType: '{"type":"float","specs":{}}',
    digit: 4,
    divide: 0,
    means: 'N',
    name: 'PH',
    required: 'T',
    path: 'PH'
  }
     */
    const {points, deviceCode, deviceSpecCode} = device;
    const topic = `/DEVICE/BASE/UPDATE/RICHTECH/${deviceSpecCode}/${deviceCode}`;
    const json = {};
    _.map(points, item => {
        const {path, dataType} = item;
        const dt = JSON.parse(dataType);
        const {type} = dt;
        json[path] = getNomData(type, path);
    });

    return {data: {reported: json}, topic};
}

function getNomData(type, path) {
    if (path === 'PH') {
        const temp = rand(730, 790);
        return temp / 100;
    }
    switch (type) {
        case 'bool':
            return rand(0, 1);
        case 'float':
            return Math.floor(Math.random() * 9);
        default :
            return rand(6, 20);
    }
}

function rand(min, max) {
    return Math.ceil(Math.random() * (max - min + 1) + min - 1);
}
